package com.wikikii.bannerlib.banner.view;

import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.render.Path;
import ohos.agp.render.PixelMapHolder;
import ohos.agp.window.service.DisplayAttributes;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;

/**
 * banner背景图
 */
public class BannerBgView extends RevealLayout implements Component.DrawTask {
    private Image imageView;
    private Path mClipPath;
    private PixelMapHolder pixelMapHolder;
    private DisplayAttributes attributes;

    /**
     * 构造函数
     *
     * @param context 上下文
     */
    public BannerBgView(Context context) {
        super(context);
        addImageView(context);
    }

    /**
     * 构造函数
     *
     * @param context 上下文
     * @param attrs   属性
     */
    public BannerBgView(Context context, AttrSet attrs) {
        super(context, attrs);
        addImageView(context);
    }

    /**
     * 构造函数
     *
     * @param context   上下文
     * @param attrs     属性
     * @param styleName 样式名
     */
    public BannerBgView(Context context, AttrSet attrs, String styleName) {
        super(context, attrs, styleName);
        addImageView(context);
    }

    /**
     * 添加图片
     *
     * @param context 上下文
     */
    public void addImageView(Context context) {
        addDrawTask(this::onDraw);
        attributes = DisplayManager.getInstance().getDefaultDisplay(getContext()).get().getRealAttributes();
        mClipPath = new Path();
        imageView = new Image(context);
        imageView.setHeight(560);
        imageView.setWidth(attributes.width);
        imageView.setScaleMode(Image.ScaleMode.CLIP_CENTER);
        this.addComponent(imageView);
    }

    /**
     * 获取图片
     *
     * @return Image
     */
    public Image getImageView() {
        return imageView;
    }

    /**
     * 重置背景图片
     *
     * @param pixelMapHolder PixelMapHolder
     */
    public void setImageHolder(PixelMapHolder pixelMapHolder) {
        if (imageView.getPixelMapHolder() != null) {
            imageView.setPixelMapHolder(null);
        }
        if (this.pixelMapHolder == null) {
            this.pixelMapHolder = pixelMapHolder;
        }
    }

    @Override
    public void onDraw(Component component, Canvas canvas) {
        mClipPath.reset();
        mClipPath.addCircle(mClipCenterX, mClipCenterY, mClipRadius, Path.Direction.CLOCK_WISE);
        canvas.save();
        canvas.clipPath(mClipPath, Canvas.ClipOp.INTERSECT);
        if (pixelMapHolder != null) {
            canvas.drawPixelMapHolder(pixelMapHolder, 0, 0, new Paint());
        }
        canvas.restore();
    }
}
